package me.leiusual.sharing.ui.cart

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.fragment_cart_home.*
import me.leiusual.sharing.R
import me.leiusual.sharing.repository.model.Data
import me.leiusual.sharing.ui.cart.adapter.CartHomeParentAdapter
import me.leiusual.sharing.ui.helper.HandleObserver
import me.leiusual.sharing.util.extension.requireValue
import me.leiusual.sharing.util.extension.spToPx
import me.leiusual.sharing.util.extension.toSpanned
import me.leiusual.sharing.util.extension.toast
import timber.log.Timber
import javax.inject.Inject

/**
 * Create by leiusual on 2018/7/15
 */
class CartHomeFragment : DaggerFragment(), View.OnClickListener {

  @Inject
  lateinit var factory: ViewModelProvider.Factory

  private val viewModel: CartHomeViewModel by viewModels { factory }

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    // 判断登录
    if (!viewModel.token.isLogin) {
      findNavController().navigate(CartHomeFragmentDirections.actionGlobalAccountLoginFragment())
    }
  }

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_cart_home, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    toolbar.setNavigationOnClickListener {
      findNavController().popBackStack()
    }

    recycler_view.adapter = CartHomeParentAdapter({
      Timber.v("选中")
      doUpdateState()

    }, { cartX ->
      Timber.v("变更：%s", cartX)
      doUpdateState()
      viewModel.cartChange(cartX.cartId, cartX.amount!!)

    }, { cartX ->
      Timber.v("删除：%s", cartX)
      doUpdateState()
      viewModel.cartRemove(cartX.cartId)
    })

    check_box.setOnClickListener(this)
    button_confirm.setOnClickListener(this)

    observeData()
    viewModel.cartList(true)
  }

  override fun onClick(v: View?) {
    when (v?.id) {
      R.id.check_box -> {

        // 全选
        doUpdateState(check_box.isChecked)
      }
      R.id.button_confirm -> {

        // 去结算
        doConfirm()
      }
    }
  }

  private fun observeData() {
    viewModel.cartList.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("cartList = %s", it)
      when (it) {
        is Data.Loading -> {
          if (viewModel.cartListFirst.requireValue) {
            state_constraint_layout.showProgress()
          }
        }
        is Data.Error -> {
          state_constraint_layout.showError(it.error.message)
        }
        is Data.Success -> {
          if (it.data.carts.isNullOrEmpty()) {
            state_constraint_layout.showEmpty()
          } else {
            state_constraint_layout.showContent()

            val adapter = recycler_view.adapter as CartHomeParentAdapter
            adapter.submitList(it.data.carts)
          }
        }
      }
    })

    viewModel.cartChange.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("cartChange = %s", it)
      when (it) {
        is Data.Loading -> {
          // ignore
        }
        is Data.Error -> {
          toast("更新失败")
        }
        is Data.Success -> {
          toast("更新成功")
        }
      }
    })

    viewModel.cartRemove.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("cartRemove = %s", it)
      when (it) {
        is Data.Loading -> {
          // ignore
        }
        is Data.Error -> {
          toast("删除失败")
        }
        is Data.Success -> {
          toast("删除成功")
        }
      }
    })

    viewModel.orderCheck.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("orderCheck = %s", it)
      when (it) {
        is Data.Loading -> {
          button_confirm.isEnabled = false
        }
        is Data.Error -> {
          button_confirm.isEnabled = true
          toast(it.error.message)
        }
        is Data.Success -> {
          button_confirm.isEnabled = true

          // 到订单确定页面
          val args = Bundle()
          val cartIdQuantity = viewModel.orderCheckParams.requireValue as HashMap
          args.putSerializable("cartIdQuantity", cartIdQuantity)
          findNavController().navigate(R.id.action_cartHomeFragment_to_cartOrderFragment, args)
        }
      }
    })
  }

  /**
   * 执行更新状态
   * @param selectedAll 是否全选
   */
  private fun doUpdateState(selectedAll: Boolean? = null) {

    // 是否有数据
    val data = viewModel.cartList.value as? Data.Success
    if (data != null) {

      // 是否全选
      if (selectedAll != null) {
        data.data.carts.forEach { cart ->
          cart.cartList.forEach { cartX ->
            cartX.checked = selectedAll
          }
        }
      }

      // 刷新列表
      recycler_view.adapter?.notifyDataSetChanged()

      // 计算合计
      var totalRmb = 0.0
      var totalJfb = 0.0
      data.data.carts.forEach { cart ->
        cart.cartList.forEach { cartX ->
          if (cartX.checked!!) {
            cartX.priceVos.forEach { priceVo ->
              when (priceVo.coinType) {
                "RMB" -> totalRmb += priceVo.pointCoin * cartX.amount!!
                else -> totalJfb += priceVo.pointCoin * cartX.amount!!
              }
            }
          }
        }
      }
      val size = 10f.spToPx(requireContext())
      val builder = StringBuilder()
      builder.append("""<font color="red">合计：""")
      builder.append("""<size_$size>￥</size_$size>""")
      builder.append(totalRmb)
      if (totalJfb > 0) {
        builder.append("""  <size_$size>分</size_$size>""")
        builder.append(totalJfb)
      }
      builder.append("""</font>""")
      text_view_total.text = builder.toString().toSpanned()
    }
  }

  /**
   * 去结算
   */
  private fun doConfirm() {

    // 是否有数据
    val data = viewModel.cartList.value as? Data.Success
    if (data != null) {

      // 获取选中的商品
      val selected = mutableMapOf<Long, Int>()
      data.data.carts.forEach { cart ->
        cart.cartList.forEach { cartX ->
          if (cartX.checked!!) {
            selected[cartX.cartId] = cartX.amount!!
          }
        }
      }

      // 检查有没有选中的商品
      if (selected.isEmpty()) {
        toast("您还没有选择商品哦")
        return
      }

      // 去服务端检查能不能下单
      viewModel.orderCheck(selected)
    }
  }
}